<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-tabs v-model="activeKey">
          <a-tab-pane tab="基本信息" key="1">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="用户账号">
              <a-input placeholder="请输入用户账号" v-decorator="['username', validatorRules.username]" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="登录密码">
              <a-input type="password" placeholder="请输入登录密码" v-decorator="['password', validatorRules.password]" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="确认密码">
              <a-input type="password" placeholder="请重新输入登录密码" v-decorator="['confirmpassword', validatorRules.confirmpassword]" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="真实姓名">
              <a-input placeholder="请输入真实姓名" v-decorator="['realname', validatorRules.realname]" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="手机号码">
              <a-input placeholder="请输入手机号码" v-decorator="['phone', validatorRules.phone]" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="电子邮件">
              <a-input placeholder="请输入电子邮件" v-decorator="['email', validatorRules.email]" :disabled="disableSubmit"/>
            </a-form-item>
          </a-tab-pane>
          
          <a-tab-pane tab="菜单权限" key="2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="角色名称">
              <a-input placeholder="租户管理员" v-decorator="['roleName', validatorRules.roleName]"/>
            </a-form-item>
            
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="角色编码">
              <a-input placeholder="tenant_admin" v-decorator="['roleCode', validatorRules.roleCode]"/>
            </a-form-item>
            
            <a-form-item
              :labelCol="{xs: { span: 24 }, sm: { span: 4 }}"
              :wrapperCol="{xs: { span: 24 }, sm: { span: 20 }}">
              <a-card title="菜单权限配置" :bordered="false">
                <a-tree
                  checkable
                  @check="onCheck"
                  :checkedKeys="checkedKeys"
                  :treeData="menuTreeData"
                  :expandedKeys="expandedKeys"
                  :showIcon="false"
                  @expand="onExpand">
                </a-tree>
              </a-card>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import { duplicateCheck } from '@/api/api'
  
  export default {
    name: "TenantAdminModal",
    data () {
      return {
        title:"创建租户管理员",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
          username:{
            rules: [
              { required: true, message: '请输入用户账号!' },
              { validator: this.validateUsername }
            ]
          },
          password:{
            rules: [
              { required: true, message: '请输入登录密码!' },
              { validator: this.validatePassword }
            ]
          },
          confirmpassword:{
            rules: [
              { required: true, message: '请重新输入登录密码!' },
              { validator: this.validateConfirmpassword }
            ]
          },
          realname:{
            rules: [{ required: true, message: '请输入真实姓名!' }]
          },
          phone:{
            rules: [{ validator: this.validatePhone }]
          },
          email:{
            rules: [{ validator: this.validateEmail }]
          },
          roleName:{
            rules: [{ required: true, message: '请输入角色名称!' }]
          },
          roleCode:{
            rules: [{ required: true, message: '请输入角色编码!' }]
          }
        },
        url: {
          add: "/sys/tenant/createTenantAdmin",
          getAllMenusWithPermission: "/sys/permission/getAllMenusWithPermission",
          queryById: "/sys/tenant/queryById"
        },
        tenantId: null,
        disableSubmit: false,
        activeKey: "1",
        menuTreeData: [],
        checkedKeys: {
          checked: [],
          halfChecked: []
        },
        expandedKeys: [],
        defaultPermissions: [
          'dashboard', 'system', 'user', 'role', 'permission', 'tenant', 'depart', 'position',
          'system:user:add', 'system:user:edit', 'system:user:delete', 'system:user:import', 'system:user:export',
          'system:role:add', 'system:role:edit', 'system:role:delete',
          'system:permission:add', 'system:permission:edit', 'system:permission:delete',
          'system:depart:add', 'system:depart:edit', 'system:depart:delete',
          'system:position:add', 'system:position:edit', 'system:position:delete'
        ]
      }
    },
    methods: {
      add (tenantId) {
        this.tenantId = tenantId;
        this.visible = true;
        this.activeKey = "1";
        
        // 重置表单和模型数据
        this.model = {};
        this.form.resetFields();
        
        // 获取租户信息，设置角色名称和编码
        this.confirmLoading = true;
        this.getTenantInfo(tenantId).then(tenantInfo => {
          const tenantName = tenantInfo.name || '未知租户';
          const roleName = `${tenantName}管理员`;
          const roleCode = this.generateRoleCode();
          
          this.$nextTick(() => {
            this.form.setFieldsValue({
              roleName: roleName,
              roleCode: roleCode
            });
            this.loadMenuTree();
          });
        }).catch(() => {
          // 如果获取租户信息失败，使用默认值
          this.$nextTick(() => {
            this.form.setFieldsValue({
              roleName: '租户管理员',
              roleCode: this.generateRoleCode()
            });
            this.loadMenuTree();
          });
        }).finally(() => {
          this.confirmLoading = false;
        });
      },
      loadMenuTree() {
        this.confirmLoading = true;
        getAction(this.url.getAllMenusWithPermission).then((res) => {
          if (res.success) {
            this.menuTreeData = this.formatTreeData(res.result);
            
            this.filterDefaultCheckedKeys();
            
            this.expandedKeys = this.getTopLevelMenuIds(this.menuTreeData);
          } else {
            this.$message.warning(res.message || '获取菜单数据失败');
          }
          this.confirmLoading = false;
        }).catch((error) => {
          this.$message.error('加载菜单失败：' + (error.message || error));
          this.confirmLoading = false;
        });
      },
      filterDefaultCheckedKeys() {
        const allKeys = this.getAllKeys(this.menuTreeData);
        
        // 过滤掉不存在的权限
        const validCheckedKeys = this.defaultPermissions.filter(key => allKeys.includes(key));
        
        if (validCheckedKeys.length === 0) {
          // 如果没有有效的默认权限，至少选择仪表盘
          const dashboardKey = allKeys.find(key => key === 'dashboard');
          if (dashboardKey) {
            validCheckedKeys.push(dashboardKey);
          }
        }
        
        this.checkedKeys = {
          checked: validCheckedKeys,
          halfChecked: []
        };
      },
      getAllKeys(treeData) {
        let keys = [];
        if (!treeData || treeData.length === 0) {
          return keys;
        }
        
        treeData.forEach(item => {
          keys.push(item.key);
          if (item.children && item.children.length > 0) {
            keys = keys.concat(this.getAllKeys(item.children));
          }
        });
        
        return keys;
      },
      formatTreeData(treeData) {
        if (!treeData || treeData.length === 0) {
          return [];
        }
        
        return treeData.map(item => {
          const key = item.id || item.key;
          
          const node = {
            title: item.title || item.name,
            key: key,
            children: []
          };
          
          if (item.children && item.children.length > 0) {
            node.children = this.formatTreeData(item.children);
          }
          
          return node;
        });
      },
      getTopLevelMenuIds(treeData) {
        return treeData.map(item => item.key);
      },
      
      // 获取租户信息
      getTenantInfo(tenantId) {
        return new Promise((resolve, reject) => {
          getAction(this.url.queryById, { id: tenantId }).then(res => {
            if (res.success) {
              resolve(res.result);
            } else {
              this.$message.warning(res.message || '获取租户信息失败');
              reject(new Error(res.message || '获取租户信息失败'));
            }
          }).catch(err => {
            this.$message.error('获取租户信息失败: ' + (err.message || err));
            reject(err);
          });
        });
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.disableSubmit = false;
        this.form.resetFields();
        this.model = {};
        this.activeKey = "1";
        this.checkedKeys = {
          checked: [],
          halfChecked: []
        };
        this.expandedKeys = [];
      },
      handleOk () {
        const that = this;
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            // 确保选中的权限数据正确格式化
            const selectedPermissions = Array.isArray(that.checkedKeys) ? that.checkedKeys : that.checkedKeys.checked;
            
            if (!selectedPermissions || selectedPermissions.length === 0) {
              that.$message.warning('请至少选择一个菜单权限');
              that.confirmLoading = false;
              return;
            }
            
            // 表单提交前数据验证
            if (!values.username || !values.password || !values.confirmpassword || !values.realname) {
              that.$message.warning('请填写必填字段');
              that.confirmLoading = false;
              return;
            }
            
            // 检查密码一致性
            if (values.password !== values.confirmpassword) {
              that.$message.warning('两次输入的密码不一致');
              that.confirmLoading = false;
              return;
            }
            
            // 处理表单数据
            let formData = Object.assign({}, values, {
              tenantId: that.tenantId,
              selectedPermissions: selectedPermissions
            });
            
            // 添加数据处理日志
            console.log('提交租户管理员数据:', formData);
            
            httpAction(that.url.add, formData, 'post').then((res) => {
              if (res.success) {
                that.$message.success(res.message || '创建租户管理员成功');
                that.$emit('ok');
                that.close();
              } else {
                that.$message.warning(res.message || '创建租户管理员失败');
              }
            }).catch((error) => {
              let errorMsg = '操作失败';
              if (error.response && error.response.data) {
                errorMsg = error.response.data.message || errorMsg;
              } else if (error.message) {
                errorMsg = error.message;
              }
              that.$message.error(errorMsg);
            }).finally(() => {
              that.confirmLoading = false;
            });
          }
        });
      },
      handleCancel () {
        this.close();
      },
      validateUsername(rule, value, callback) {
        if (value) {
          let pattern = /^[a-zA-Z0-9_]{5,}$/;
          if(!pattern.test(value)){
            callback('用户名不符合规则，请输入字母、数字、下划线且不少于5位');
            return;
          }
          
          let params = {
            tableName: 'sys_user',
            fieldName: 'username',
            fieldVal: value,
            dataId: this.model.id
          };
          duplicateCheck(params).then(res => {
            res['success'] ? callback() : callback(res['message'])
          }).catch(err => {
            callback(err.message || err)
          });
        } else {
          callback();
        }
      },
      validatePassword(rule, value, callback) {
        if (value) {
          if (value.length < 6) {
            callback('密码长度不能小于6位');
            return;
          }
          
          // 密码强度校验
          let passwordStrength = this.checkPasswordStrength(value);
          if (passwordStrength === 'weak') {
            callback('密码强度太弱，请包含字母、数字和特殊字符');
            return;
          }
          
          // 如果确认密码已经输入，则需要再次验证确认密码
          const confirmPassword = this.form.getFieldValue('confirmpassword');
          if (confirmPassword) {
            this.form.validateFields(['confirmpassword'], { force: true });
          }
          callback();
        } else {
          callback();
        }
      },
      validateConfirmpassword(rule, value, callback) {
        const password = this.form.getFieldValue('password');
        if (value && value !== password) {
          callback('两次输入的密码不一致');
        } else {
          callback();
        }
      },
      validatePhone(rule, value, callback) {
        if (value) {
          // 中国大陆手机号验证
          if (!(/^1[3456789]\d{9}$/.test(value))) {
            callback('请输入正确的手机号码');
            return;
          }
          
          // 检查手机号是否已存在
          let params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.model.id
          };
          duplicateCheck(params).then(res => {
            res['success'] ? callback() : callback(res['message'])
          }).catch(err => {
            callback(err.message || err)
          });
        } else {
          callback();
        }
      },
      validateEmail(rule, value, callback) {
        if (value) {
          // 邮箱格式验证
          if (!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))) {
            callback('请输入正确的电子邮件');
            return;
          }
          
          // 检查邮箱是否已存在
          let params = {
            tableName: 'sys_user',
            fieldName: 'email',
            fieldVal: value,
            dataId: this.model.id
          };
          duplicateCheck(params).then(res => {
            res['success'] ? callback() : callback(res['message'])
          }).catch(err => {
            callback(err.message || err)
          });
        } else {
          callback();
        }
      },
      onCheck(checkedKeys, info) {
        this.checkedKeys = {
          checked: checkedKeys,
          halfChecked: info.halfCheckedKeys || []
        };
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
      },
      // 生成随机角色编码：时间戳+随机数
      generateRoleCode() {
        const timestamp = new Date().getTime();
        const random = Math.floor(Math.random() * 10000);
        return `tenant_${timestamp}_${random}`;
      },
      // 检查密码强度
      checkPasswordStrength(password) {
        let hasLetter = /[a-zA-Z]/.test(password);
        let hasDigit = /\d/.test(password);
        let hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password);
        
        if ((hasLetter && hasDigit) || (hasLetter && hasSpecial) || (hasDigit && hasSpecial)) {
          return 'strong';
        } else if (hasLetter || hasDigit || hasSpecial) {
          return 'medium';
        } else {
          return 'weak';
        }
      },
    }
  }
</script>

<style scoped>
/* 可以添加一些自定义样式 */
.ant-card-body {
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
}
</style> 